﻿using System;
using System.Collections.Generic;
using Suk.Common;
using Suk.Interface;
using Suk.Interface.Admin;
using Suk.Models;
using Suk.Models.Admin;

namespace Suk.Service.Admin
{
    public class UserService : BaseService<User>, IUserInterface
    {
        public override List<User> FindEntity(User m, ref int totalCount, int pageIndex = 1, int pageSize = 10)
        {

            int UserGroupId = m.UserGroupId;
            if (UserGroupId == 0 || UserGroupId == 9999)
            {
                return base.FindEntity(ref totalCount, pageIndex, pageSize);
            }
            else
            {

                return db.Queryable<User, UserGroupRelation>((t, g) => new object[] {
                         SqlSugar.JoinType.Left,t.Id==g.UserId}).Where((t, g) => g.UserGroupId == UserGroupId)
                        .OrderBy(t => t.Id).ToPageList(pageIndex, pageSize, ref totalCount);
            }
        }

        public override int Insert(User model)
        {
            int identityid = base.Insert(model);

            var relation = db.Queryable<UserGroupRelation>().Where(t => t.UserGroupId == model.UserGroupId & t.UserId == identityid).ToList();
            if (relation.Count == 0)
            {
                UserGroupRelation d = new UserGroupRelation();
                d.UserGroupId = model.UserGroupId;
                d.UserId = identityid;
                db.Insertable(d).ExecuteCommand();
            }

            return identityid;
        }

    }
}
